package com.ztman.rxjava;

import com.luck.picture.lib.rxbus2.RxBus;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
 * Created by YJH on 2017/12/6.
 * 功能：RxBus 消息通知类-总指挥
 */

public class RxBusCommander {

    private static volatile RxBusCommander mInstance;
    private final Subject bus;


    public RxBusCommander() {
        bus = new SerializedSubject<>(PublishSubject.create());
    }

    /**
     * 功能：单例模式RxBus
     *
     * @return
     */
    public static RxBusCommander getInstance() {

        RxBusCommander rxBus = mInstance;
        if (mInstance == null) {
            synchronized (RxBus.class) {
                rxBus = mInstance;
                if (mInstance == null) {
                    rxBus = new RxBusCommander();
                    mInstance = rxBus;
                }
            }
        }

        return rxBus;
    }


    /**
     * 功能：判断是否有订阅者,发送指令消息
     *
     * @param object
     */
    public void postCommander(Object object) {
        if (bus.hasObservers())
            bus.onNext(object);

    }

    /**
     * 功能：接收指令消息
     *
     * @param eventType
     * @param <T>
     * @return
     */
    public <T> Observable<T> receiveCommander(Class<T> eventType) {
        return bus.ofType(eventType);
    }
}
